/* 
 * File:   DeliveryActivity.cpp
 * Author: bd
 * 
 * Created on March 26, 2011, 5:14 PM
 */

#include "DeliveryActivity.hpp"

#include <boost/thread.hpp>
#include <iostream>

#include "Application.hpp"
#include "ShortMsgItem.hpp"
#include "DeliveryClient.hpp"
#include "inc.hpp"

DeliveryActivity::DeliveryActivity(const DeliveryActivity& orig) :
Activity(orig.name_, orig.config_, orig.pool_)
{
}

DeliveryActivity::DeliveryActivity(const std::string& name, const Configuration& config, Pool<ShortMsgItem>& pool) :
Activity(name, config, pool)
{
}

DeliveryActivity::~DeliveryActivity()
{
}

void DeliveryActivity::start()
{
    client_ = DeliveryClientFactory::create(config_.targetConnStr());
    if (client_ == NULL)
        return;

    client_->connect();

    while (Application::monitor.get() == true)
    {
        bool ind;
        ShortMsgItem item = pool_.inputQueue()->pop(ind);
        if (ind == false)
        {
            LOG(INFO) << "input queue is empty..." << "\n";
            wait();
        }
        else
        {
            item.handler = name_;

            this->send(item);

            if (item.status == ShortMsgItem::SUCCESS || item.retry >= config_.maxItemRetry())
            {
                pool_.outputQueue()->push(item);
            }
            else if (item.status == ShortMsgItem::FAIL)
            {
                item.retry++;
                pool_.inputQueue()->push(item);
            }
            wait();
        }
    }
    stop();
}

void DeliveryActivity::stop()
{
    LOG(INFO) << name_ << " end!" << "\n";
}

void DeliveryActivity::send(ShortMsgItem& item)
{
    using namespace boost::posix_time;

    client_->send(item);
#if 0
    if (item.id % 10 == 0)
        item.status = ShortMsgItem::FAIL;
    else
#endif
        item.status = ShortMsgItem::SUCCESS;

    item.lastUpdate = second_clock::local_time();

}
//operators

//void DeliveryActivity::operator()()
//{
//    start();
//    boost::this_thread::sleep(boost::posix_time::seconds(10));
//    std::cout<<"wait\n";
//    stop();
//}
